package file;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Base64;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FileChannelTest {
	
	public static void main(String[] args) throws FileNotFoundException, IOException {
		
		ExecutorService threads = Executors.newFixedThreadPool(4);
		for(int i = 0; i < 4; i++){
			threads.execute(()->{
				try {
					RandomAccessFile file = open("append.txt");
					for(int j = 0; j < 10; j++){
						appendLine(file, Thread.currentThread().getName() + j);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			});
		}
	}
	
	public static RandomAccessFile open(String fileName) throws IOException{
		File file = new File(fileName);
		boolean isNew = false;
		if(!file.exists()){
			file.createNewFile();
			isNew = true;
		}
		
		RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
		if(isNew){
			randomAccessFile.writeLong(0);
			randomAccessFile.write("\r\n".getBytes());
		}
		return randomAccessFile;
	}
	
	/**获取浮标，加共享锁 
	 * @throws IOException */
	public static long getCursor(RandomAccessFile file) throws IOException{
		long pos = file.getFilePointer();
		file.seek(0);
		long cursor = file.readLong();
		file.seek(pos);
		return cursor;
	}
	
	public static void setCursor(RandomAccessFile file, long cursor) throws IOException{
		if(cursor >= 0){
			long pos = file.getFilePointer();
			file.seek(0);
			file.writeLong(cursor);
			file.write("\r\n".getBytes());
			file.seek(pos);
		}
	}
	
	public static String readLine(RandomAccessFile file) throws IOException{
		long cursor = getCursor(file);
		if(cursor <= 0){
			file.readLine();
		}else{
			file.seek(cursor);
		}
		String line = file.readLine();
		setCursor(file, file.getFilePointer());
		return line;
	}
	
	public static void appendLine(RandomAccessFile file, String line) throws IOException{
		if(file != null){
			long cursor = getCursor(file);
			if(cursor < 0){
				setCursor(file, 0);
				file.readLine();
			}else{
				file.seek(cursor);
			}
			file.write(Base64.getEncoder().encode(line.getBytes()));
			file.write("\r\n".getBytes());
		}
	}
}
